﻿using Caliburn.Micro;
using MarcelloDB.Platform;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using WarColors.Core.Injection;
using WarColors.Data.Marcello;
using WarColors.ViewModels;
using WarColors.Views;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace WarColors.UWP
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App
    {
        private WinRTContainer winContainer;
        private IInjectionContainer container;

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
        }

        protected override void Configure()
        {
            winContainer = new WinRTContainer();
            container = new SimpleInjectionContainer(winContainer);
            winContainer.RegisterWinRTServices();

            container.
                Singleton<Application>();

            RegisterServices().ContinueWith(result =>
            {
                Coroutine.Completed += (s, e) =>
                {
                    if (e.Error == null)
                        return;

                    Debug.Write(e.Error.Message);
                };
            });
        }

        private async Task RegisterServices()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            var folder = await localFolder.CreateFolderAsync("WarColorsData", CreationCollisionOption.OpenIfExists);

            container
                    .RegisterHandler(typeof(IDatabase), container => new Database(container.GetInstance<IPlatform>(), folder.Path));

            container
                .PerRequest<IPlatform, MarcelloDB.uwp.Platform>();
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            Initialize();

            Xamarin.Forms.Forms.Init(e, Rg.Plugins.Popup.Windows.Popup.GetExtraAssemblies());

            Window.Current.Content = new HostView();
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }

        protected override void PrepareViewFirst(Frame rootFrame)
        {
            var navigation = winContainer.RegisterNavigationService(rootFrame);
            var navigationManager = SystemNavigationManager.GetForCurrentView();

            navigation.Navigated += (s, e) =>
            {
                navigationManager.AppViewBackButtonVisibility = navigation.CanGoBack
                    ? AppViewBackButtonVisibility.Visible
                    : AppViewBackButtonVisibility.Collapsed;
            };
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            yield return typeof(App).GetTypeInfo().Assembly;
            yield return typeof(ProjectListViewModel).GetTypeInfo().Assembly;
            yield return typeof(ProjectListView).GetTypeInfo().Assembly;
        }

        protected override object GetInstance(Type service, string key)
        {
            return container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        protected override void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }


    }
}
